package com.store.app.activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.R;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.Utils;
import com.store.app.widget.BookedOnlinePopupWindow;
import com.store.app.widget.ProgressWebView;
import com.store.app.widget.ShareDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.json.JSONObject;

/**
 * 领了么==>淘淘领
 */
public class WebViewLLMActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, OnClickListener{
    private TextView tv, tv_right;
    private ProgressWebView webView;
    private String title;
    private String urls = "", id = "";
    private LinearLayout  lin_right;
    private ProgressBar progressBar;
    private SwipeRefreshLayout mSwipeLayout;
    private LinearLayout lin_all;
    private RelativeLayout loadfail;
    private LinearLayout lin_loadNull;//加载为空
    private LinearLayout lin_loadfail;  //无网络页面
    private TextView tvReload;
    private BookedOnlinePopupWindow bp_online;
    private PopupWindow mPop;
    private final int POST_SUCC = 8;
    private final int POST_FAIL = 9;
    private String errorMsg;
    private GoToLogin goToLogin;

    private UMImage image;//分享时候的图标
    private String shareTitle;//分享标题
    private String shareText;//分享内容
    private ShareDialog mShareDialog;//分享时候的弹窗
    private UMShareAPI mShareAPI;
    private View tv_Right1;//此页面当分享按钮
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case POST_SUCC:
                    dismissProgressDialog();
                    Toast.makeText(WebViewLLMActivity.this, "您的订单已提交，供应商将安排工作人员在24小时内确认订单并协商配送事宜，谢谢合作。", Toast.LENGTH_LONG).show();
                    break;
                case POST_FAIL:
                    dismissProgressDialog();
                    if (!TextUtils.isEmpty(errorMsg)) {
                        Toast.makeText(WebViewLLMActivity.this, errorMsg, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };


    public WebViewLLMActivity() {
        super();
    }

    private String from = "";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_webview);
        urls = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        try {
            from = getIntent().getStringExtra("from");
        } catch (Exception e) {
            from = "";
        }
        goToLogin = new GoToLogin(this);
        ((TextView)findViewById(R.id.tvTitle)).setText(title);
        findViews();
        setWebView();
        Log.v("zyl","current build:"+Build.VERSION.SDK_INT );
    }


    private void setWebView() {
        webView.clearCache(true);
        webView.loadUrl(urls);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置不使用缓存
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
       //********************
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        //********************

        webView.setWebViewClient(new WebViewClient1()
//			@Override
//			public boolean shouldOverrideUrlLoading(WebView view, String url) {
//				Log.v("zyl", "shouldOverrideUrlLoading:" + url);
//				if (url.contains("/wholesale/detail")) {
//					Log.v("zyl", "包含");
//					Intent intent = new Intent (WebViewBookedActivity.this,WebViewBooked2Activity.class);
//					intent.putExtra("url",  url);
//					intent.putExtra("title", "我要批");
//					startActivity(intent);
//
//				} else {
//					Log.v("zyl", "不包含");
//				}
//				if (url.startsWith("http:") || url.startsWith("https:")) {
//					return false;
//				}
//
//				// Otherwise allow the OS to handle things like tel, mailto, etc.
//				try {
//					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//					startActivity(intent);
//				} catch (Exception e) {
//				}
//				return true;
//			}
        );
        webView.setWebChromeClient(new WebChromeClient1());
        webView.addJavascriptInterface(new JSInterface(), "jsObj");
//        webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
//            @Override
//            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
//                if (webView.getScrollY() == 0) {
//                    mSwipeLayout.setEnabled(true);
//                } else {
//                    mSwipeLayout.setEnabled(false);
//                }
//            }
//        });
        webView.setLister(new onScrollList() {
            @Override
            public void onScrollChate(boolean state) {
                Log.v("zyl","state :"+state);
                if(state){
                    mSwipeLayout.setEnabled(true);
                }else{
                    mSwipeLayout.setEnabled(false);
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_ll_right:
                if ("wyp".equals(from)) {
                    Intent intent = new Intent(WebViewLLMActivity.this,TheSingleOrderActivity.class);
                    intent.putExtra("showFragmentIndex","1");
                    startActivity(intent);
//                    Intent intent = new Intent(WebViewBookedActivity.this, WebViewSearchActivity.class);
//                    startActivity(intent);
//					String[] mPermissionList = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CALL_PHONE,Manifest.permission.READ_LOGS,Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.SET_DEBUG_APP,Manifest.permission.SYSTEM_ALERT_WINDOW,Manifest.permission.GET_ACCOUNTS};
//					ActivityCompat.requestPermissions(WebViewBookedActivity.this, mPermissionList, 100);
                } else if ("cjf".equals(from)) {
//                    Intent intent = new Intent(WebViewBookedActivity.this, WebViewBooked2Activity.class);
//                    intent.putExtra("title", "领了么");//==>淘淘领
//                    intent.putExtra("url", SettingData.FREE_HELP);
//                    startActivity(intent);

                } else {                    finish();
                }
                break;
            case R.id.tv_right1:

                //跳转到订单页面，默认显示领样
                Intent intent = new Intent(WebViewLLMActivity.this, TheSingleOrderActivity.class);
                intent.putExtra("showFragmentIndex","2");
                startActivity(intent);

                /**
                 * 分享功能，隐藏
                 */
//                mShareDialog = new ShareDialog(WebViewBookedActivity.this, listener);
//                mShareDialog.show();
                break;
        }
    }

    public interface onScrollList{
        void onScrollChate(boolean state);
    }

    final class JSInterface {

        private Handler handler = new Handler();


        @JavascriptInterface
        public void storeGetFreeSucc() {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "店东领取成功，跳转到订单页面");
                    Intent intent = new Intent(WebViewLLMActivity.this, TheSingleOrderActivity.class);
                    intent.putExtra("showFragmentIndex", "2");//2代表免费领样的Fragment
                    startActivity(intent);
                }
            }, 1500);
        }


        @JavascriptInterface
        public void scan(final String string) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "scan:" + string);
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        String goods_code = jsonObject.getString("goods_code");
                        String goods_url = jsonObject.getString("goods_url");
                        String amount = jsonObject.getString("amount");
                        Intent intent = new Intent(WebViewLLMActivity.this, FreeScanActivity.class);
                        intent.putExtra("goods_code", goods_code);
                        intent.putExtra("goods_url", goods_url);
                        intent.putExtra("amount", amount);
                        startActivity(intent);
                    } catch (Exception e) {
                    }

                }

            });
        }

        //打开广告页
        @JavascriptInterface
        public void openAdLayer(final String jsonData) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "openAdLayer jsonData:" + jsonData);
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String url = jsonObject.getString("url");
                        Intent intent = new Intent(WebViewLLMActivity.this, WebViewAdActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }

        // 供JS调用
        public void logout(String str) {

        }
    }

    public void showLoadResult(int state) {
        //无网络情况
        if (state == 1) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.VISIBLE);
            lin_loadNull.setVisibility(View.GONE);
        }//无数据情况
        else if (state == 2) {
            Log.v("zyl", "无数据");
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.GONE);
            lin_loadNull.setVisibility(View.VISIBLE);
        }//都不显示
        else {
            loadfail.setVisibility(View.GONE);
        }
    }

    public class WebViewClient1 extends android.webkit.WebViewClient {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {                 // Handle the error
            Log.v("zyl", "onReceivedError网络加载不出来");
//            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);

            //停止webView的所有操作
            webView.onPause();
            webView.pauseTimers();
//			lin_loadfail.setVisibility(View.VISIBLE);
            showLoadResult(1);
//			Toast.makeText(WebViewBookedActivity.this,"description:"+description,Toast.LENGTH_SHORT).show();
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.v("zyl", "变化的URL:" + url);
            if (url.contains("wholesale/detail")) {
                Log.v("zyl", "包含");
                Intent intent = new Intent(WebViewLLMActivity.this, WebViewBooked2Activity.class);
                intent.putExtra("url", url);
                intent.putExtra("title", "我要批");
                startActivity(intent);
                return true;
            } else if(url.contains("free/detail")){
                Intent intent = new Intent(WebViewLLMActivity.this, FreeDetailsWebViewActivity.class);
                intent.putExtra("url", url);
                intent.putExtra("title", "淘淘领");//领了么==>淘淘领
                startActivity(intent);
                return true;
            }else {
                Log.v("zyl", "不包含");
            }
            if (url.startsWith("http:") || url.startsWith("https:")) {
                return false;
            }

            // Otherwise allow the OS to handle things like tel, mailto, etc.
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
            } catch (Exception e) {

            }
            return true;
//			view.loadUrl(url);
//			return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.v("zyl", "onPageStart:" + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (url.startsWith("http")) {
                urls = url;
            }
        }

    }

    public class WebChromeClient1 extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.v("zyl", "加载进度：" + newProgress);
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                if (progressBar.getVisibility() == View.GONE)
                    progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }


    }

    public void onPause() {//继承自Activity
        super.onPause();
        webView.onPause();

        webView.pauseTimers();
        if (isFinishing()) {
            Log.v("zyl", "isFinishing");
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    public void onResume() {//继承自Activity
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }

    private void findViews() {

        tv_Right1 = findViewById(R.id.tv_right1);
        tv_Right1.setOnClickListener(this);
        lin_right = (LinearLayout) findViewById(R.id.public_ll_right);
//		lin_right.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
////				if(title.equals("免费领")){
////					Log.v("zyl","是惠金币类型");
////					startActivity(new Intent(WebViewBookedActivity.this,GoldBalanceActivity.class));
////				}else{
////					跳到搜索页面
//					if("wyp".equals(from)){
//						Intent intent = new Intent(WebViewBookedActivity.this,WebViewSearchActivity.class);
//						startActivity(intent);
//					}
//
////					finish();
////				}
//			}
//		});
        lin_right.setOnClickListener(this);
        tv_right = (TextView) findViewById(R.id.public_tv_right);
//		if(title.equals("免费领")){
//			tv_right.setText("金币明细");
//		}else{
//			tv_right.setText("关闭");
//		}


            tv_right.setVisibility(View.GONE);
        tv_right.setText("");
            tv_Right1.setVisibility(View.VISIBLE);
            tv_Right1.setBackgroundResource(R.drawable.pic_new_older_icon);

        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        loadfail = (RelativeLayout) findViewById(R.id.loadfail);

        lin_loadfail = (LinearLayout) findViewById(R.id.ll_load_fail);//无网络
        lin_loadNull = (LinearLayout) findViewById(R.id.ll_load_null);//无网络
        tvReload = (TextView) findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                showLoadResult(3);
                webView.clearCache(true);
                webView.clearHistory();
                webView.clearFormData();
                webView.loadUrl(urls);
            }
        });
        lin_all = (LinearLayout) findViewById(R.id.lin_all);
        webView = (ProgressWebView) findViewById(R.id.onlcon_web);
        webView.setContext(this);
        findViewById(R.id.public_ll_return).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
                    webView.goBack();// 返回前一个页面
                } else {
                    finish();
                }
            }
        });
//		lin_loadfail.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				lin_loadfail.setVisibility(View.GONE);
//				webView.clearCache(true);
//				webView.clearHistory();
//				webView.clearFormData();
//				webView.loadUrl(urls);
//			}
//		});

        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.sw);
        mSwipeLayout.setOnRefreshListener(this);
        mShareAPI = UMShareAPI.get(this);
        image = new UMImage(WebViewLLMActivity.this, R.drawable.pic_icon_share_logo);
        shareTitle = "天上真的会掉馅饼哦,你敢来,我敢送!";
        shareText = "欢迎光临每天惠旗下门店咨询";
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        setWebView();
        mSwipeLayout.setRefreshing(false);
    }


    ShareDialog.OnShareClickListener listener = new ShareDialog.OnShareClickListener() {
        @Override
        public void FriendCircle(View v) {
            new ShareAction(WebViewLLMActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(LocationApplication.shareURL)
                    .share();
            mShareDialog.dismiss();
        }

        @Override
        public void WeChatFriends(View v) {
            new ShareAction(WebViewLLMActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(LocationApplication.shareURL)
                    .share();
            mShareDialog.dismiss();
        }

        @Override
        public void QQFriends(View v) {
            new ShareAction(WebViewLLMActivity.this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(LocationApplication.shareURL)
                    .share();
            mShareDialog.dismiss();

        }

        @Override
        public void QQZone(View v) {
            new ShareAction(WebViewLLMActivity.this).setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(LocationApplication.shareURL)
                    .share();
            mShareDialog.dismiss();
        }

        @Override
        public void Copy(View v) {

        }

        @Override
        public void SMS(View v) {

        }


        @Override
        public void Email(View v) {
        }
    };
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {

            Toast.makeText(WebViewLLMActivity.this, " 分享成功啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(WebViewLLMActivity.this, " 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            if ("QQ".equals(platform.toString())) {
                // Toast.makeText(ShareApplicationActivity.this, " 分享成功啦", Toast.LENGTH_SHORT).show();
            } else {
//                Toast.makeText(WebViewBookedActivity.this, " 分享取消了", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }
}
